<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Exception;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Address extends Api
{

    /**
     * Address模型对象
     * @var \app\admin\model\Address
     */
    protected $model = null;

    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Address;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 地址列表
     * @return void
     */
    public function index()
    {
        try {
            $where = ['user_id' => $this->auth->id];
            $list = $this->model->where($where)->paginate(20);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('查询成功', $list);
    }

    /**
     * 新增地址
     * @return void
     */
    public function add()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Address';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "add")) {
                throw new Exception($validate->getError());
            }

            $where = ['default' => 1];
            $default = $this->model->where($where)->find();

            if ($default) {
                $default->save(['default' => 0]);
            }

            $params["user_id"] = $this->auth->id;
            $this->model->allowField(true)->save($params);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('新增成功');
    }

    /**
     * 地址详情
     * @return void
     */
    public function info()
    {
        $params = $this->request->param();

        try {
            $where = ['id' => $params['id']];
            $data = $this->model->where($where)->find();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('查询成功', $data);
    }

    /**
     * 编辑地址
     * @return void
     */
    public function edit()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Address';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "edit")) {
                throw new Exception($validate->getError());
            }

            if ($params['default'] == 1) {
                $where = ['default' => 1];
                $default = $this->model->where($where)->find();

                if ($default) {
                    $default->save(['default' => 0]);
                }
            }

            $params["user_id"] = $this->auth->id;
            $this->model->allowField(true)->save($params, ['id' => $params['id']]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('编辑成功');
    }

    /**
     * 删除地址
     * @return void
     */
    public function delete()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {
            $this->model->destroy($params['id']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }

    /**
     * 默认地址修改
     * @return void
     */
    public function defaultChange()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            $where = ['default' => 1];
            $default = $this->model->where($where)->find();

            if ($default) {
                $default->save(['default' => 0]);
            }

            $this->model->save(['default' => 1], ['id' => $params['id']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('修改成功');
    }

    /**
     * 经纬度转换省市区
     * @return void
     */
    public function regeo()
    {
        $params = $this->request->param();
        try {
            $url = "https://restapi.amap.com/v3/geocode/regeo";

            // 使用ThinkPHP内置的Http客户端发送请求
            $response = Http::get($url, [
                'key' => 'a4e01fe75cb0209bf24deaaf26c2c414',
                'location' => $params['location'],
            ]);

            // 将JSON响应转换为数组
            $data = json_decode($response);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('转换成功', $data);
    }
}
